const fs = require( 'fs' );
const path = require( 'path' );
const express = require( 'express' );

const customerFiles = 'customers' ;

const router = express.Router();

const customers = [
    { id : 1 , username : 'sanfeng' , password: 'wudang'  } ,
    { id : 2 , username : 'guoxiang' , password: 'helloemei'  } ,
    { id : 3 , username : 'yongnian' , password: 'helloguoxiang' }
];

router.post( '/sign/up' , (req,resp) => {
    let username = req.body.username ;
    let password = req.body.password ;
    let confirm = req.body.confirm ;

});

router.post( '/check/username' , (req,resp) => {
    let username = req.body.username ;
    console.log( username );
    // 数组的 find 函数在调用 condition 函数时会为其传入三个参数
    let condition = function( x ){
        return x.username === username ;
    }
    // Array.prototype.find 是个高阶函数
    let c = customers.find( condition );
    let m ;
    // 若 c 存在则为 true ，就表示该用户名被占用
    if( c ){
        m = { state: 'fail' , message: '用户名被占用' }
    } else {
        m = { state: 'success' , message: '用户名可用' }
    }
    // 将对象转换为JSON格式字符串后再发送给浏览器
    resp.json( m );
});

// 路由: 打开登录页面
router.get( '/sign/in' , (req,resp) => {
    resp.render( 'sign-in' );
});

// 路由: 处理登录请求
router.post( '/sign/in' , (req,resp) => {
    // 从表单中获取用户输入的用户名和密码
    let uname = req.body.username ;
    let passwd = req.body.password ;

    // 首先应该作数据校验

    let filepath = path.resolve( customerFiles , uname + '.txt' );

    // 判断文件是否存在(同步方法)
    if( fs.existsSync( filepath ) ){
        // 读取文件内容(同步方法)
        let content = fs.readFileSync( filepath , 'utf8' );
        let customer = JSON.parse( content );
        if( passwd == customer.password ) {
            // 准予登录
            // 1、将用户信息保存到会话(session)对象中
            req.session.customer = customer ;
            // 2、重定向到某个页面
            resp.redirect( '/customer/home' );
        } else {
            resp.render( 'sign-in' , { message: '密码错误' });
        }
    } else { // 若 filepath 对应的文件不存在则说明用户名是错误的
        resp.render( 'sign-in' , { message: '用户名错误' });
    }

});

router.get( '/home' , (req,resp)=>{
    console.log( req.headers );
    console.log( req.cookies );
    console.log( req.session );
    resp.render( 'home' , { customer: req.session.customer } );
});

router.get( '/sign/out' , (req,resp)=>{
    delete req.session.customer ;
    resp.render( 'home' );
});

module.exports = router ;